<template>
  <div class="bunch">
    <div class="search">
      <el-input
        placeholder="请输入分组名称"
        clearable
        v-model="inputValue"
        class="input-with-select"
      >
        <el-button
          slot="append"
          @click="handleSearch"
          icon="el-icon-search"
        ></el-button>
      </el-input>
      <div class="add" @click="dialogFormVisible">
        <span><i class="el-icon-plus"></i></span>商品分组
      </div>
      <!-- <div class="adds">
        <span><i class="el-icon-plus"></i></span>新建商品
      </div> -->
    </div>
    <!-- 表格 -->
    <div class="table">
      <el-table
        :data="filteredTableData"
        ref="tableRef"
        border
        style="width: 100%"
        :height="autoHeight"
        @expand-change="expandChange"
        row-key="id"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table :data="list" border style="padding: 0">
              <el-table-column prop="id" label="商品id"> </el-table-column>
              <el-table-column prop="name" label="商品名称"> </el-table-column>
              <el-table-column prop="price" label="商品价格"> </el-table-column>
              <el-table-column align="center" label="商品图片">
                <template slot-scope="scope">
                  <img
                    style="height: 80px; width: 80px"
                    :src="$imgUrl(scope.row.picUrl.split(',')[0])"
                    alt=""
                  />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="commodityCustomizeGroup.id" label="分组id">
        </el-table-column>
        <el-table-column prop="commodityCustomizeGroup.createTime" label="日期">
        </el-table-column>
        <el-table-column prop="commodityCustomizeGroup.name" label="分组名称">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center">
              <el-button
                @click="handleClick(scope.row.commodityCustomizeGroup)"
                type="primary"
                icon="el-icon-edit"
                circle
              ></el-button>
              <el-button
                @click="cancelDel(scope.row.commodityCustomizeGroup)"
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
              <!-- <el-button circle icon="el-icon-plus" type="warning"></el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <!-- <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div> -->
    <!-- 新建分组 -->
    <div class="is">
      <el-dialog
        @close="close"
        title="新建分组"
        :visible.sync="dialogFormVisibleShow"
        :close-on-click-modal="false"
      >
        <div>分组名称:</div>
        <el-input
          type="text"
          class="input"
          v-model="xgValue"
          placeholder="请输入分组名称"
        ></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancels">取 消</el-button>
          <el-button type="primary" @click="addFz">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 编辑 -->
    <div class="is">
      <el-dialog
        @close="closeTwo"
        title="编辑分组"
        :visible.sync="dialogFormVisibleShowTwo"
        :close-on-click-modal="false"
      >
        <div>分组名称:</div>
        <el-input
          type="text"
          class="input"
          v-model="xgValueTwo"
          placeholder="请输入分组名称"
        ></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelsTwo">取 消</el-button>
          <el-button type="primary" @click="addFzTwo">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getShopInfo,
  showShopCommodity,
  addShopCommodity,
  delShopCommodity,
  editShopCommodity,
} from "@/api/user";
import { getLoginUserGroupCommodityList } from "@/api/commodity";
export default {
  data() {
    return {
      currentPage4: 1,
      pageSize: 10,
      inputValue: "",
      tableData: [],
      filteredTableData: [], // 过滤后的表格数据
      total: 0,
      dialogFormVisibleShow: false,
      dialogFormVisibleShowTwo: false,
      xgValue: "",
      xgValueTwo: "",
      xgList: [],
      popconfirmVisible: false,
      ids: [],
      groupId: "",
      list: [],
    };
  },
  mounted() {
    if (localStorage.getItem("shop")) {
      this.shopId = JSON.parse(localStorage.getItem("shop")).id;
    }
    this.getShopInfos();
    this.showShopCommodity();
    // this.getCommodityLists()
  },
  computed: {
    //动态高度
    autoHeight() {
      return window.innerHeight - 160;
    },
  },
  methods: {
    expandChange(row, b) {
      if (!b.length) return;
      if (this.row) {
        if (row.id == this.row.id) {
          return
         }
        this.$refs.tableRef.toggleRowExpansion(this.row, false);
        this.row = row;
        this.list = []
        this.getCommodityLists(row.commodityCustomizeGroup.id);
        return;
      }
      this.row = row;
      this.getCommodityLists(row.commodityCustomizeGroup.id);
    },
    //根据分组获取商品列表
    getCommodityLists(id) {
      const jsonObject = {
        shopId: this.shopId,
        type: 1,
        groupId: id,
      };
      getLoginUserGroupCommodityList(jsonObject)
        .then((res) => {
          console.log(res.data, "列表");
          if (res.data) {
            this.list = res.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //搜索
    handleSearch() {
      if (this.inputValue) {
        // 如果有输入值，则过滤表格数据
        this.filteredTableData = this.tableData.filter((item) =>
          item.commodityCustomizeGroup.name.includes(this.inputValue)
        );
      } else {
        // 如果没有输入值，则显示所有数据
        this.filteredTableData = this.tableData;
      }
    },
    //点击编辑出现的弹窗
    handleClick(item) {
      this.dialogFormVisibleShowTwo = true;
      //   console.log(item, "000");
      this.xgValueTwo = item.name;
      this.groupId = item.id;
    },
    //每页多少条（10）
    // handleSizeChange(val) {
    //   this.pageSize = val
    // //   this.currentPage4 = 1;
    //   this.showShopCommodity();
    // },
    //第几页
    // handleCurrentChange(val) {
    //   this.currentPage4 = val;
    // //   console.log(this.currentPage4,'02');
    //   this.showShopCommodity();
    // },
    //获取id
    getShopInfos() {
      getShopInfo()
        .then((res) => {
          // console.log(res.data.shop.id);
          localStorage.setItem("shop", JSON.stringify(res.data.shop));
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取分组信息
    showShopCommodity() {
      const jsonObject = {
        shopId: this.shopId,
      };
      showShopCommodity(jsonObject)
        .then((res) => {
          if (!res.data) return;
          this.tableData = res.data;
          console.log(this.tableData, "获取分组信息");
          // this.total = this.tableData.length;
          this.filteredTableData = this.tableData.map((item) => {
            item.id = item.commodityCustomizeGroup.id;
            return item;
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //新建分组的弹窗
    dialogFormVisible() {
      this.dialogFormVisibleShow = true;
    },
    //取消分组的弹窗
    cancels() {
      this.dialogFormVisibleShow = false;
      this.xgValue = "";
    },
    //取消编辑的弹窗
    cancelsTwo() {
      this.dialogFormVisibleShowTwo = false;
      this.xgValueTwo = "";
    },
    close() {
      this.xgValue = "";
    },
    closeTwo() {
      this.xgValueTwo = "";
    },
    //新建分组
    addFz() {
      // 检查是否有重复的分组名称
      const isDuplicate = this.tableData.some(
        (group) => group.commodityCustomizeGroup.name == this.xgValue
      );
      if (isDuplicate) {
        this.$message.error("分组名称已存在，请输入不同的名称！");
        return;
      }
      if (!this.xgValue) {
        this.$message.error("请输入分组名称!");
        return;
      }
      this.xgList.push(this.xgValue);
      const jsonObject = {
        shopId: this.shopId,
        groupNames: this.xgList,
      };
      addShopCommodity(jsonObject).then((res) => {
        this.xgList = [];
        this.showShopCommodity();
        this.dialogFormVisibleShow = false;
        this.$message({
          type: "success",
          message: "新建成功!",
        });
      });
    },
    //点击删除-删除取消
    cancelDel(item) {
      if (item.commoditySortIds) {
        return this.$message({
          type: "error",
          message: "有商品的分组不可删除!",
        });
      }
      this.ids = item.id;
      console.log(this.ids);
      this.$confirm("此操作将删除该分组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delShopCommoditys();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delShopCommoditys() {
      const jsonObject = {
        shopId: this.shopId,
        groupId: this.ids,
      };
      delShopCommodity(jsonObject).then((res) => {
        this.showShopCommodity();
      });
    },
    //编辑分组
    addFzTwo() {
      const jsonObject = {
        shopId: this.shopId,
        name: this.xgValueTwo,
        groupId: this.groupId,
      };
      editShopCommodity(jsonObject).then((res) => {
        // console.log(res);
        this.showShopCommodity();
        this.dialogFormVisibleShowTwo = false;
      });
    },
  },
};
</script>
<style lang="less" scoped>
.bunch {
  width: 100%;
  // height: 650px;
  border-radius: 10px;
  background: white;
  padding: 10px;

  .search {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .el-input {
      width: 400px;
    }

    .input-with-select .el-input-group__prepend {
      background-color: #fff;
    }

    .add {
      margin-left: 15px;
      background: #009af2;
      padding: 5px;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      min-width: 95px;
      span {
        margin-right: 5px;
      }
    }
  }

  .table {
    // max-height: 500px;
    overflow-y: auto;

    /* 自定义滚动条样式 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
      width: 4px;
      height: 4px;
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
      background-color: #f1f1f1;
      border-radius: 5px;
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
      background-color: #009af2;
      border-radius: 5px;
    }
  }

  .block {
    margin-top: 20px;
  }

  .is {
    ::v-deep .el-dialog {
      min-width: 300px;
      width: 500px;
      border-radius: 5px;
    }

    .input {
      margin-top: 10px;
      width: 250px;
      height: 40px;
      padding-left: 5px;
    }
  }

  ::v-deep .el-table__expanded-cell {
    padding: 0;
  }
}
</style>